package cn.iune.erp.customer;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;




@Repository
public class FileCustomerDaoJPAImpl extends BaseJPAImpl<FileCustomer> implements IFileCustomerDao {

	
//	private String kSql;
//	@PersistenceContext 
//	private EntityManager em ;

	/*
	public FileCustomerDaoJPAImpl(){
		em = EntityManagerService.getU2EMFactory().createEntityManager();
	}
	*/

	@Override
	public void insert(FileCustomer obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
//		FileCustomer obj = em.find(FileCustomer.class, fID);
		em.remove(em.getReference(FileCustomer.class, fID));
	}

	@Override
	public FileCustomer update(FileCustomer obj) {
		FileCustomer objNew = em.merge(obj);
		return objNew;
	}

	@Override
	public FileCustomer getByID(String fID) {
		FileCustomer singleResult = em.find(FileCustomer.class, fID);
		return singleResult;
	}

	@Override
	public List<FileCustomer> getAll() {
		Query query = em.createNamedQuery("FileCustomer.findAll");
		@SuppressWarnings("unchecked")
		List<FileCustomer> resultList = query.getResultList();
		return resultList;
	}

	
	@Override
	public FileCustomer getByNo(String customerNo, String enterpriseNo) {
		//1、定义sql语句
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE ( FileCustomer.customerNo = :customerNo ) "
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("customerNo", customerNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		FileCustomer singleResult = null;
		try{
			singleResult = (FileCustomer) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}
	
	
	@Override
	public FileCustomer getByMemberNo(String memberNo, String enterpriseNo) {
		//1、定义sql语句
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE ( FileCustomer.memberNo = :memberNo ) "
				+ " AND ( FileCustomer.isMember = 1 ) "
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("memberNo", memberNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		FileCustomer singleResult = null;
		try{
			singleResult = (FileCustomer) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}

	@Override
	public FileCustomer getByLoginName(String sLoginName, String enterpriseNo) {
//		System.out.println("通过登录名查询客户对象！");
		// TODO Auto-generated method stub
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE FileCustomer.sLoginName = :sLoginName"
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("sLoginName", sLoginName);
		query.setParameter("enterpriseNo", enterpriseNo);
		
		FileCustomer singleResult = null;
		try {
			singleResult = (FileCustomer) query.getSingleResult();
		} catch (NoResultException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		return singleResult;
	}


	@Override
	public List<FileCustomer> getList(String enterpriseNo) {
		// TODO Auto-generated method stub
		String kSql="SELECT FileCustomer"
				+ " FROM FileCustomer FileCustomer "
				+ " WHERE FileCustomer.enterpriseNo = :enterpriseNo"
				;
		Query query = em.createQuery(kSql);
		query.setParameter("enterpriseNo", enterpriseNo);
		
		@SuppressWarnings("unchecked")
		List<FileCustomer> resultList = query.getResultList();
		return resultList;
	}

	
	@Override
	public FileCustomer getByMobilePhone(String sMobilePhone, String enterpriseNo) {
		//1、定义sql语句
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE ( FileCustomer.sMobilePhone = :sMobilePhone ) "
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("sMobilePhone", sMobilePhone);
		query.setParameter("enterpriseNo", enterpriseNo);
		FileCustomer singleResult = null;
		try{
			singleResult = (FileCustomer) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}
	
	@Override
	public FileCustomer getByMobilePhone(String sMobilePhone, int isMember, String enterpriseNo) {
		//1、定义sql语句
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE ( FileCustomer.sMobilePhone = :sMobilePhone ) "
				+ " AND ( FileCustomer.isMember = :isMember ) "
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("sMobilePhone", sMobilePhone);
		query.setParameter("isMember", isMember);
		query.setParameter("enterpriseNo", enterpriseNo);
		FileCustomer singleResult = null;
		try{
			singleResult = (FileCustomer) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}
	

	@Override
	public FileCustomer getByOgnID(String ognID, String enterpriseNo) {
//		System.out.println("通过登录名查询客户对象！");
		// TODO Auto-generated method stub
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE FileCustomer.ognID = :ognID"
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("ognID", ognID);
		query.setParameter("enterpriseNo", enterpriseNo);
		
		FileCustomer singleResult = null;
		try {
			singleResult = (FileCustomer) query.getSingleResult();
		} catch (NoResultException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return singleResult;
	}
	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(FileCustomer.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}

	@Override
	public JSONObject query(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		/*
		limit-->15
		offset-->0
		filters-->[unitCode LIKE ? OR unitName LIKE ? OR unitType LIKE ?]
		sqlParams-->[%3%, %3%, %3%]
		*/		
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "FileCustomer.*"
				
				//会员余额
//				+ ",(FileCustomer.memberAmount - FileCustomer.allocatedAmount) as pendingAmount"

				//				+ ",FileCustomerAddress.fAddress"
//				+ ",FileCustomerAddress.fAddressDetail"
//				+ ",FileCustomerAddress.contacts"
//				+ ",FileCustomerAddress.mobilePhone"
//				+ ",FileCustomerAddress.fPhone"
				;
		
		String from = "FileCustomer FileCustomer"
//		String from = "FileCustomer FileCustomer LEFT JOIN FileCustomerAddress FileCustomerAddress ON (FileCustomerAddress.fMasterID = FileCustomer.fID AND FileCustomerAddress.iDefault=1)"
				;

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("customerNo LIKE ? OR customerName LIKE ? OR sMobilePhone LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
				//System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
        //获取数据访问权限///////////////////////////////////////////////////////////////////////
		/*
		String url = data.getString("url");
		String dataAccessPerm = SecurityService.getDataAccessPerm(url);
		if("private".equals(dataAccessPerm)){
			//私有
			filters.add("FileCustomer.userId='"+SecurityService.getCurrentPerson().getsID()+"'");
		}
		if("protected".equals(dataAccessPerm)){
			//保护，需要根据数据权限管理
			System.out.println("url存在-->此url已经启用数据权限管理！");
			
			List<String> fids = SecurityService.getDataAccessIDs();
//			System.out.println("fids-->"+fids);
			String da = "";
			if(fids!=null){
				for(String fid :fids){
					da = da + " OR FileCustomer.employeeNo like '%" + fid + "%'";
				}
			}
			
			filters.add("FileCustomer.userId='"+SecurityService.getCurrentPerson().getsID()+"'"+da);
		}
		*/
		/////////////////////////////////////////////////////////////////////////////////////
		
		String where = " WHERE 1=1 ";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		
		//System.out.println("where-->"+where);
		
		
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT ShopCart.fID FROM ShopCart ShopCart    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
//		json.put("dataAccessPerm", dataAccessPerm);
		
		return json;
	}

	@Override
	public JSONObject queryUNION(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		/*
		limit-->15
		offset-->0
		filters-->[unitCode LIKE ? OR unitName LIKE ? OR unitType LIKE ?]
		sqlParams-->[%3%, %3%, %3%]
		*/		
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "FileCustomer.*"
				
				+ ",FileCustomerAddress.fAddressName"
				+ ",FileCustomerAddress.fAddress"
				+ ",FileCustomerAddress.fAddressDetail"
				
				+ ",FileCustomerAddress.fProvince AS fProvince"
				+ ",FileCustomerAddress.fCity AS fCity"
				+ ",FileCustomerAddress.fZone AS fZone"
				
				+ ",FileCustomerAddress.contacts AS contacts"
				+ ",FileCustomerAddress.mobilePhone AS mobilePhone"
				+ ",FileCustomerAddress.fPhone AS fPhone"
				;
		
//		String from = "FileCustomer FileCustomer"
		String from = "FileCustomer FileCustomer LEFT JOIN FileCustomerAddress FileCustomerAddress ON (FileCustomerAddress.fMasterID = FileCustomer.fID AND FileCustomerAddress.iDefault=1)"
				;

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("customerNo LIKE ? OR customerName LIKE ? OR sMobilePhone LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
        //获取数据访问权限///////////////////////////////////////////////////////////////////////
		/*
		String url = data.getString("url");
		String dataAccessPerm = SecurityService.getDataAccessPerm(url);
		if("private".equals(dataAccessPerm)){
			//私有
			filters.add("FileCustomer.userId='"+SecurityService.getCurrentPerson().getsID()+"'");
		}
		if("protected".equals(dataAccessPerm)){
			//保护，需要根据数据权限管理
			System.out.println("url存在-->此url已经启用数据权限管理！");
			
			List<String> fids = SecurityService.getDataAccessIDs();
//			System.out.println("fids-->"+fids);
			String da = "";
			if(fids!=null){
				for(String fid :fids){
					da = da + " OR FileCustomer.employeeNo like '%" + fid + "%'";
				}
			}
			
			filters.add("FileCustomer.userId='"+SecurityService.getCurrentPerson().getsID()+"'"+da);
		}
		*/
		/////////////////////////////////////////////////////////////////////////////////////
		
		String where = " WHERE 1=1 ";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		
		System.out.println("where-->"+where);
		
		
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT ShopCart.fID FROM ShopCart ShopCart    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
//		json.put("dataAccessPerm", dataAccessPerm);
		
		return json;
	}

	
	/*
	@Override
	public FileCustomer getByNo(String customerNo, String enterpriseNo) {
		// TODO Auto-generated method stub
		//1、定义sql语句
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE ( FileCustomer.customerNo = :customerNo ) "
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("customerNo", customerNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		FileCustomer singleResult = null;
		try{
			singleResult = (FileCustomer) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
			
		}
		
		return singleResult;
	}
	*/
	
	@Override
	public FileCustomer getByName(String customerName, String enterpriseNo) {
		// TODO Auto-generated method stub
		//1、定义sql语句
		String kSql="SELECT FileCustomer FROM FileCustomer FileCustomer "
				+ " WHERE ( FileCustomer.customerName = :customerName ) "
				+ " AND ( FileCustomer.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("customerName", customerName);
		query.setParameter("enterpriseNo", enterpriseNo);
		FileCustomer singleResult = null;
		try{
			singleResult = (FileCustomer) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}


	/*
	public JSONObject query(JSONObject data) throws Exception {
		
		// 获取参数
		Object columns = data.getJSONObject("columns"); // 列定义
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		
		
		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		if (!CommonService.isEmptyString(search)) {
			// 增加过滤条件
			filters.add("unitCode LIKE ? OR unitName LIKE ? OR unitType LIKE ?");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		//处理过滤条件
		if (!CommonService.isEmptyString(filter)) {
			filters.add(filter);
		}

		
		// 按用户ID过滤，用于主从数据示例
		
//		String userID = data.getString("userID");
//		if (!CommonService.isEmptyString(userID)) {
//			filters.add("fUserID = ?");
//			sqlParams.add(userID);
//		}
		
		
		Table table = null;
		// 获取数据源连接
		Connection conn = Util.getConnection(DATASOURCE_U2);
		try {
			// 执行单表数据查询，返回Table
			table = Util.queryData(conn, TABLE_U2_FILEUNIT, columns, filters, "cDatetime DESC", sqlParams, offset, limit);
		} finally {
			// 必须关闭数据源连接
			conn.close();
		}
		
		JSONObject json = Transform.tableToJson(table);

		return json;
	}

	public int save(JSONObject object) throws Exception {
		// TODO Auto-generated method stub

		log.info("@RequestParam------"+object.toJSONString());
		// JSON转换Table
		Table table = Transform.jsonToTable(object);

		// 获取数据源连接
		Connection conn = Util.getConnection(DATASOURCE_U2);
		try {
			// 开启事务
			conn.setAutoCommit(false);
			try {
				// 保存Table
				Util.saveData(conn, table, TABLE_U2_FILEUNIT);
				// 提交事务
				conn.commit();
			} catch (SQLException e) {
				// 如果发生异常，首先回滚事务，然后把异常继续抛出
				conn.rollback();
				throw e;
			}
		} finally {
			// 必须关闭数据源连接
			conn.close();
		}

		return 0;
	}
	*/
	
}
